package com.dataseek.iot.device.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import net.logstash.logback.encoder.org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class FileUploadService {
    //设置允许上传文件格式
    private static final String[] IMAGE_TYPE=new String[]{".bmp",".jpg",".jpeg",".png",".gif",".mp3",".mp4",".mkv"};
//
//    @Autowired
//    private OSSClient ossClient;

    @Autowired
    private OssConfig ossConfig;

    private static OSSClient ossClient;

    @PostConstruct
    public void setOssClient() {
        if (ossClient == null) {
            String endPoint = ossConfig.getEndPoint();
            String accessKeyId = ossConfig.getAccessKeyId();
            String accessKeySecret = ossConfig.getAccessKeySecret();
            ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        }
    }


    public String upload(MultipartFile file){
        String bucketName=ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint();
//        String accessKeyId = ossConfig.getAccessKeyId();
//        String accessKeySecret = ossConfig.getAccessKeySecret();
        String prefix = ossConfig.getPrefix();

        //返回的Url
        String returnUrl="";
        //审核上传文件是否符合规定格式
        boolean isLegal=false;
        for (String type:IMAGE_TYPE){
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
                isLegal=true;
                break;
            }
        }
        if (!isLegal){
            //如果不正确返回错误状态码
            return "上传文件不合法";
        }
        //获取文件的名称
        String originalFilename = file.getOriginalFilename();
        //截取文件类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        //最终保存文件名称
        String newFileName= UUID.randomUUID().toString()+ fileType;
        //构建日期路径  ps ：oss目标文件夹/yyyy/MM/dd文件名称
        String filePath=new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        //文件上传文件的路径
        String uploadUrl=prefix+"/"+filePath+"/"+newFileName;
        //获取文件输入流
        InputStream inputStream=null;
        try{
            inputStream=file.getInputStream();

        }catch (IOException e){
            e.printStackTrace();
        }

        //文件上传到阿里云oss
        //ossClient.putObject(bucketName,uploadUrl,inputStream);//,meta
        ossClient.putObject(bucketName,uploadUrl,inputStream);//,meta
        returnUrl="http://"+bucketName+"."+endPoint+"/"+uploadUrl;
        return returnUrl;
    }

    /**
     * 下载
     * @param filePath
     * @return
     */
    public void downLoad(String filePath){
        try {
            String[] strings = filePath.split("com/");
            String[] temps = strings[1].split("/");
            String specifiedName = temps[temps.length-1];
            ossClient.getObject(new GetObjectRequest(ossConfig.getBucketName(), strings[1]), new File(ossConfig.getLocalPath()+"/"+specifiedName));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     * @param filePath
     * @return
     */
    public Integer DeleteFile(@RequestParam String filePath){
        Integer status;
        try{
            String[] strings = filePath.split("com/");
            ossClient.deleteObject(ossConfig.getBucketName(), strings[1]);
            status =  HttpStatus.OK.value();
        }catch (Exception e){
            status = HttpStatus.EXPECTATION_FAILED.value();
            e.printStackTrace();
        }
        return status;
    }
}
